var o;
avalon.ready(function(){
    o = avalon.define({
        $id:"root",
        infor:{},
        tubuy:false,
        isfocu:false,
        isfoc:false,
        isbaoben:false,
        hand:1,
        timeitem:1,
        mingxi:1,
        topen:false,
        fastfoc:false,
        buy:function(){
            o.tubuy = true;
            if(o.fastfoc == true) {
                location.href = "trade/order_list";
            }
        },
        topay:function(){
            o.tubuy = false;
            location.href="trade/order_list";
        },
        ChooseFocu:function(){
            o.isfocu = !o.isfocu;
        },
        ChooseFoc:function(){
            o.isfoc = !o.isfoc;
        },
        ChooseBao:function(){
            o.isbaoben = !o.isbaoben;
        },
        switchtime:function(timId){
            o.timeitem=timId;
        },
        switchMin:function(minId){
            o.mingxi=minId;
        },
        switchhand:function(handId){
            o.hand=handId;
        },
        opentime:function(){
            o.topen = !o.topen;
        },
        Fastfoc:function(){
            o.fastfoc = !o.fastfoc;
        }
    });
    avalon.scan(document.body);

});
//加载基本信息
function loadQuery(){
    RPC.invokeApi("","",null,null,function(){
        widgetUtil.loadding("加载中...");
    },function(n){
        widgetUtil.hideWidget();
//      o.infor=n.result;
    },function(){
        widgetUtil.hideWidget();
    });
}
// 基于准备好的dom，初始化echarts实例
var myChart = echarts.init(document.getElementById('section02'));
var categoryData = new Array();
var values = new Array();
var volumes= new Array();
var average= new Array();
var m5=new Array();
var m10=new Array();
var m30=new Array();

var lineType=0;
var lastClose;//昨日收盘
var timerPro;
var time_num=10;//实时查询频率 10代表 10秒刷新一次
var orderSubmit=false;

// 初始 option
option = {

    animation: false,//加载效果
    tooltip : {//点击提示
        trigger: 'axis',
        triggerOn:'mousemove',
        showDelay: 500,             // 显示延迟，添加显示延迟可以避免频繁切换，单位ms
        hideDelay: 0,            // 隐藏延迟，单位ms
        transitionDuration : 0.4,  // 动画变换时间，单位s
        backgroundColor: 'rgba(0,0,0,0.7)',     // 提示背景颜色，默认为透明度为0.7的黑色
        borderColor: '#333',       // 提示边框颜色
        borderRadius: 4,           // 提示边框圆角，单位px，默认为4
        borderWidth: 0,            // 提示边框线宽，单位px，默认为0（无边框）
        padding: 5,                // 提示内边距，单位px，默认各方向内边距为5，
                                   // 接受数组分别设定上右下左边距，同css
        position: function (pos, params, el, elRect, size) {
            var obj = {top: 10};
            obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
            return obj;
        },
        // axisPointer: {          //虚线
        //     type: 'cross'
        // },
        // formatter:function (params) {
        //     var seriesType=params[0].seriesType;
        //     var res = params[0].name;
        //     if(seriesType == 'line'){
        //         res += '<br/>  数值 : ' + params[0].value;
        //     }
        //     if(seriesType == 'candlestick'){
        //         res += '<br/>  开盘 : ' + params[0].value[0];
        //         res += '<br/>  收盘 : ' + params[0].value[1];
        //         res += '<br/>  最高 : ' + params[0].value[3];
        //         res += '<br/>  最低 : ' + params[0].value[2];
        //     }
        //     return res;
        // }
    },
    axisPointer: {
        link: {xAxisIndex: 'all'},
        label: {
            backgroundColor: '#777'
        }
    },
    visualMap: {
        show: false,
        seriesIndex: 0,
        dimension: 2,
        pieces: [{
            value: 1,
            color: '#ef232a'
        }, {
            value: -1,
            color: '#14b143'
        }]
    },
    grid: [{  //控制图形位置
        left: 10,
        right:10,
        top: 15,
        height: 200,
        width:'95%'
    },
        {
            left: 10,
            right:10,
            top: 240,
            height: 50,
            width:'95%'
        }
    ],
    xAxis: [{
        type: 'category',
        data : categoryData,
        scale: true,
        boundaryGap :true,//false 从0开始
        axisLine: {onZero: false,lineStyle: { color: '#777' }},
        axisTick: {show: true},
        axisLabel:{show: true,color: '#fff' },
        splitLine: {show: true,lineStyle: { color: '#212228' }},
        splitNumber: 20,
        min: 'dataMin',
        max: 'dataMax',
        axisPointer: {
            z: 100
        }
    },
        {
            type: 'category',
            gridIndex: 1,
            data: categoryData,
            scale: true,
            boundaryGap : false,
            splitLine: {show: false},
            axisLabel: {show: false},
            axisTick: {show: false},
            axisLine: { lineStyle: { color: '#777' } },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            axisPointer: {
                label: {
                    formatter: function (params) {
                        var seriesValue = (params.seriesData[0] || {}).value;
                        return params.value
                            + (seriesValue != null
                                    ? '\n' + echarts.format.addCommas(seriesValue)
                                    : ''
                            );
                    }
                }
            }
        }],
    dataZoom: [],//区域拖动
    yAxis: [
        {
            scale: true,
            splitNumber: 2,
            show:true,//是否显示刻度
            interval: 100000,//调整间隔
            // min: 'dataMin',
            // max: 'dataMax',
            axisLine: { lineStyle: { color: '#1d1e23' } },
            splitLine: { show: false },//分割线
            axisTick: { show: false },
            axisLabel: { //刻度标签
                inside: true,
                showMinLabel: true,
                showMaxLabel: true,
                formatter: function (value, index) {
                    return parseInt(value);
                },
                textStyle: {
                    color: function (value, index) {
                        return value >= lastClose ? 'red' : 'green';
                    }
                },
                fontWeight:'bold',
                fontFamily:'Microsoft YaHei'
            }
        },
        {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            axisLabel: {show: false},
            axisLine: {show: false},
            axisTick: {show: false},
            splitLine: {show: false}
        }],
    series: [
        {
            name: '成交量',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: volumes
        },
        {
            name: '分时线',
            type: 'line',
            data: values,
            showSymbol: false,
            //symbol:'none',
            smooth: true,//这句就是让曲线变平滑的
            lineStyle: {
                normal: {
                    width: 0.5,//,opacity: 0.5
                    color:'#fff'
                },
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: '#626262'
                    }, {
                        offset: 1,
                        color: '#626262'
                    }])
                }
            }

        },
        {
            name: '均线',
            type: 'line',
            data: average,
            showSymbol: false,
            //symbol:'none',
            smooth: true,//这句就是让曲线变平滑的
            lineStyle: {
                normal: {
                    width: 0.5,//,opacity: 0.5
                    color:'#ff730b'
                },
            }
        },
        {
            name: 'k线',
            type: 'candlestick',
            data: [],
            itemStyle: {
                normal: {
                    color: '#ef232a',
                    color0: '#14b143',
                    borderColor: '#ef232a',
                    borderColor0: '#14b143'
                }
            },
            tooltip: {
                formatter:function (params) {
                    var seriesType=params[0].seriesType;
                    var res = params[0].name;
                    if(seriesType == 'line'){
                        res += '<br/>  数值 : ' + params[0].value;
                    }
                    if(seriesType == 'candlestick'){
                        res += '<br/>  开盘 : ' + params[0].value[0];
                        res += '<br/>  收盘 : ' + params[0].value[1];
                        res += '<br/>  最高 : ' + params[0].value[3];
                        res += '<br/>  最低 : ' + params[0].value[2];
                    }
                    return res;
                }
            }
        },
        {
            name: 'M5',
            type: 'line',
            data: [],
            showSymbol: false,
            smooth: true,//这句就是让曲线变平滑的
            lineStyle: {
                normal: {
                    width: 0.5,//,opacity: 0.5
                    color:'#ff171c'
                },
            }
        },
        {
            name: 'M10',
            type: 'line',
            data: [],
            showSymbol: false,
            smooth: true,//这句就是让曲线变平滑的
            lineStyle: {
                normal: {
                    width: 0.5,//,opacity: 0.5
                    color:'#ff730b'
                },
            }
        },
        {
            name: 'M30',
            type: 'line',
            data: [],
            showSymbol: false,
            smooth: true,//这句就是让曲线变平滑的
            lineStyle: {
                normal: {
                    width: 0.5,//,opacity: 0.5
                    color:'#13ff4b'
                },
            }
        }


    ]
};


if (option && typeof option === "object") {
    myChart.setOption(option, true);
}


function toLoadView(line) {
    lineType=line;
    $.ajax({
        type: "POST",
        url:"/trade/getKdata",
        data:{code:$("#code").val(),type:lineType},
        dataType: "json",
        error: function(){
            layer.open({
                type: 2
                ,content: '加载中',
                time:1
            });
        },
        success: function(obj) {
            if(obj != ''&& obj.code!=0){
                var data;
                if(lineType==0){
                    data=JSON.parse(obj.data).Data;
                    lastClose= JSON.parse(obj.data).LastClose;
                }else {
                    m5=[],m10=[],m30=[];
                    data=JSON.parse(obj.data);

                    // var dataM5=JSON.parse(obj.kM5);
                    // for(var i=0;i<dataM5.length;i++){
                    //     m5.push(dataM5[i].Close);
                    // }
                    //
                    // var dataM10=JSON.parse(obj.kM10);
                    // for(var i=0;i<dataM10.length;i++){
                    //     m10.push(dataM10[i].Close);
                    // }
                    // var dataM30=JSON.parse(obj.kM30);
                    // for(var i=0;i<dataM30.length;i++){
                    //     m30.push(dataM30[i].Close);
                    // }
                }

                values=[],categoryData=[],volumes=[],average=[];

                //for(var i=data.length-1;i>=0;i--){

                var price;
                if(lineType==0) {
                    for(var i=0;i<data.length;i++) {
                        price = data[i].Trend;
                        values.push(data[i].Trend);
                        categoryData.push(new Date(parseInt(data[i].Date)).Format("hh:mm:ss"));
                        average.push(data[i].Average);
                        volumes.push([i, data[i].Volume, data[i].Trend > lastClose ? 1 : -1]);


                        // if (i <= 10) {
                        //     addDetailData(new Date(parseInt(data[i].addTime)).Format("yyyy-MM-dd hh:mm:ss"), price, data[i].volume, 0, '多开', i == 0 ? 0 : 1);
                        // }
                    }
                }else {
                    for(var i=data.length-1;i>=0;i--) {
                        price = data[i].Close;

                        // 数据意义：开盘(open)，收盘(close)，最低(lowest)，最高(highest)
                        values.push([data[i].Open, data[i].Close, data[i].Low, data[i].High]);
                        categoryData.push(new Date(parseInt(data[i].Date)).Format("hh:mm:ss"));
                        volumes.push([i, data[i].Volume, data[i].Close > data[i].Open ? 1 : -1]);

                        // if(i<=10){
                        //     addDetailData(new Date(parseInt(data[i].Date)).Format("yyyy-MM-dd hh:mm:ss"),price,data[i].Volume,0,'多开',i==0?0:1);
                        // }
                    }
                }



                setOption();//设置线型
            }else {
                //信息框
                layer.open({
                    content: obj.msg
                    ,btn: '我知道了'
                });
            }
        }
    });
}

/* 根据选择的k线设置图形 */
function setOption(){
    if(lineType==0){
        showL();
    }else {
        showK();
    }
    /* 启动定时 查询数据*/
    // clearInterval(timerPro);
    // timerPro=setInterval(getProuctFreshData,1000*time_num);
}
/*显示k线*/
function showK() {
    myChart.setOption({
        xAxis: [{
            data: categoryData
        },{
            data: categoryData
        }],
        dataZoom: [//区域拖动
            {
                id: 'dataZoomX',
                type: 'inside',
                zoomLock:true,//只能平移，不能缩放
                xAxisIndex: [0,1],
                start: 50,//数据窗口范围的起始百分比。范围是：0 ~ 100。表示 0% ~ 100%。
                end: 100
            }
        ],
        series: [
            {
                name:'成交量',
                data: volumes
            },
            {
                name:'分时线',
                data: [],
                markLine:{
                    data:[]
                }
            },
            {
                name:'均线',
                data: []
            },
            {
                name:'k线',
                data: values
            },
            {
                name:'M5',
                data: m5
            },
            {
                name:'M10',
                data: m10
            },
            {
                name:'M30',
                data: m30
            }
        ]
    });
}

/*显示分时线线*/
function showL() {
    myChart.setOption({
        xAxis: [{
            data: categoryData
        },{
            data: categoryData
        }],
        dataZoom: [//区域拖动
            {
                id: 'dataZoomX',
                type: 'inside',
                zoomLock:true,//只能平移，不能缩放
                xAxisIndex: [0,1],
                start: 0,//数据窗口范围的起始百分比。范围是：0 ~ 100。表示 0% ~ 100%。
                end: 100
            }

        ],
        series: [
            {
                name:'成交量',
                data: volumes
            },
            {
                name:'分时线',
                data: values,
                markLine: {
                    symbol: ['none', 'none'],
                    silent: true,
                    lineStyle: {
                        normal: {
                            width: 0.5,//,opacity: 0.5
                            color:'#fff'
                        }
                    },
                    data: [
                        {
                            name: '收盘价标线',
                            yAxis: lastClose
                        }
                    ]
                }
            },
            {
                name:'均线',
                data: average
            },
            {
                name:'k线',
                data: []
            },
            {
                name:'M5',
                data: []
            },
            {
                name:'M10',
                data: []
            },
            {
                name:'M30',
                data: []
            }
        ]
    });
}

/*查询产品列表价格*/
function getProuctFreshData(){
    $.ajax({
        type: "POST",
        url:"/trade/getFreshData",
        data:{code:$("#code").val(),type:lineType},
        dataType: "json",
        success: function(obj){
            if(obj!= ''){
                toChangeHead(obj);
                toChangeK(obj);
            }
        }
    });
}
/** 实时更新产品价格 */
function toChangeHead(new_data) {
    $('#new_price').text(new_data.last_price);//最新价格
    $('#change_val').text(new_data.change_count);//变化量
    $('#change_point').text(new_data.change_count);//变化百分比
    $('#change_v').text(new_data.change_count);//变化速度

    $('#high').text(new_data.high);
    $('#low').text(new_data.low);
    $('#open').text(new_data.open);
    $('#close').text(new_data.close);

    addDetailData(new Date(parseInt(new_data.add_time)).Format("yyyy-MM-dd hh:mm:ss"),new_data.last_price,new_data.volume,new_data.change_count,'多开',1);

}

/*实时更新K线价格 */
var c_fenshitu_data;
var c_fenshitu_data_time;
function toChangeK(new_data) {
    var new_price=new_data.last_price;
    var data_time=new_data.add_time;

    if(lineType==0){

        if(c_fenshitu_data*100==new_price*100&&c_fenshitu_data_time==data_time){
            return;
        }else{
            values.push(new_price);
            categoryData.push(new Date(data_time).Format("hh:mm:ss"));
            values.shift();
            categoryData.shift();
            c_fenshitu_data = new_price;
            c_fenshitu_data_time = data_time;
        }
    }
    setOption();
}

/** 增加交易记录数据*/
function addDetailData(addtime,price,xianshou,zcang,kp,add_type) {
    if(add_type==0){//切换图形
        $('.detail_datas').html('');
    }
    var data_dom='<div class="detail_title hidden f12 mb10">'
        +'<div class="w40 fl color_ef">'+addtime+'</div>'
        +'<div class="w15 fl tr">'+price+'</div>'
        +'<div class="w15 fl tr">'+xianshou+'</div>'
        +'<div class="w15 fl tr color_ef">'+zcang+'</div>'
        +'<div class="w15 fl tr color_ef">'+kp+'</div>'
        +'</div>';

    $('.detail_datas').prepend(data_dom);
}
